package io.github.uicdb.et.capability;

import io.github.uicdb.et.ModElements;
import io.github.uicdb.et.fluid.ElementStream;
import lombok.RequiredArgsConstructor;
import net.neoforged.neoforge.fluids.FluidStack;
import net.neoforged.neoforge.fluids.capability.IFluidHandler;
import org.jetbrains.annotations.NotNull;

@RequiredArgsConstructor
public class ElementalAsFluid implements IFluidHandler {

    public final IElementalHandler handler;

    @Override
    public int getTanks() {
        return ModElements.values().length;
    }

    @Override
    public @NotNull FluidStack getFluidInTank(int i) {
        ModElements modElements = ModElements.values()[i];
        return new FluidStack(modElements.getElemental().getFluidSource(), handler.getElemental(modElements));
    }

    @Override
    public int getTankCapacity(int i) {
        return handler.getElementalCapacity(ModElements.values()[i]);
    }

    @Override
    public boolean isFluidValid(int i, FluidStack fluidStack) {
        return fluidStack.getFluid() instanceof ElementStream.Source source && ModElements.byHolder(source.getElementalObject().getElementHolder()).getIndex() == i;
    }

    @Override
    public int fill(FluidStack fluidStack, @NotNull FluidAction fluidAction) {
        if (fluidStack.getFluid() instanceof ElementStream.Source source) {
            return handler.fillElemental(fluidStack.getAmount(), ModElements.byHolder(source.getElementalObject().getElementHolder()), fluidAction.execute() ? IElementalHandler.ElementalAction.EXECUTE : IElementalHandler.ElementalAction.SIMULATE);
        }
        return 0;
    }

    @Override
    public @NotNull FluidStack drain(FluidStack fluidStack, @NotNull FluidAction fluidAction) {
        if (fluidStack.getFluid() instanceof ElementStream.Source source) {
            var ret = handler.drainElemental(fluidStack.getAmount(), ModElements.byHolder(source.getElementalObject().getElementHolder()), fluidAction.execute() ? IElementalHandler.ElementalAction.EXECUTE : IElementalHandler.ElementalAction.SIMULATE);
            return new FluidStack(fluidStack.getFluid(), ret);
        }
        return FluidStack.EMPTY;
    }

    @Override
    public FluidStack drain(int i, FluidAction fluidAction) {
        ModElements elements = ModElements.values()[i];
        int re = handler.drainElemental(handler.getElemental(elements), elements, fluidAction.execute() ? IElementalHandler.ElementalAction.EXECUTE : IElementalHandler.ElementalAction.SIMULATE);
        return re <= 0 ? FluidStack.EMPTY : new FluidStack(elements.getElemental().getFluidSource(), re);
    }
}
